<?php

namespace Admin\Controller;
use Admin\Common\Category;
use Admin\Logic\CateLogic;


class CateController extends CommonController
{
    public function index()
    {
        // 获取分类列表
        $cate = CateLogic::getAll();
        if (!empty($cate)) {
            $cate = Category::toLevel($cate);
        }
        
        $this->assign('cate',$cate);
        $this->display();
    }

    // 展示添加页面
    public function add()
    {
        // 获取分类列表
        $cate = $data = CateLogic::getAll();
        $cate = Category::toLevel($cate);
        $this->assign('cate', $cate);
        $this->display();
    }

    // 展示修改页面
    public function edit()
    {
        $id = I('get.id', 0, 'intval');

        if ($id < 1) {
            E('非法操作');
        }

        $cate = D('cate')->where(['id' => $id])->find();
        $this->assign('cate', $cate);
        $this->display();

    }

    /**
     *添加分类处理
     */
    public function store()
    {
        $this->checkPost();

        $param = [
            'cate_name' => I('post.cate_name', '', 'htmlspecialchars'),
            'parent_id' => I('post.parent'),
            'is_show' => I('post.is_show') == 'on' ? 1 : 0,
            'order_sort' => I('post.order_sort'),
            'created_at' => getDateTime()
        ];
        $cate = CateLogic::create($param);

        if ($cate['code'] == 1) {
            return $this->ajaxError($cate['msg']);
        } else {
            return $this->ajaxSuccess();
        }
    }


    /**
     * 修改分类信息处理
     * @return string
     */
    public function update()
    {
        $this->checkPost();

        // 接受数据
        $param = [
            'id' => I('post.id', 0, 'intval'),
            'cate_name' => I('post.cate_name'),
            'order_sort' =>  I('post.order_sort', 1, 'intval'),
            'code' =>  sprintf('%04s', I('post.code')),
            'is_show' => I('post.is_show')=='on'?1:0,
            'update_at' => date('Y-m-d H:i:s')
        ];

        // 执行修改
        $result = CateLogic::update($param);

        if ($result === false) {
            return $this->ajaxError('服务器找不到啦~^_^');
        }

        return $this->ajaxSuccess();



    }

    public function delete()
    {
        $id = I('get.id', 0, 'intval');

        $data = CateLogic::delete($id);

        if (json_decode($data,true)['code'] > 0) {
            return $this->ajaxSuccess();
        } else {
            return $this->ajaxError(json_decode($data,true)['errorMsg']);
        }
    }



}